home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / Miro_Downloader.exe / unittest.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-11-12  |  29.7 KB  |  916 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''
  5. Python unit testing framework, based on Erich Gamma\'s JUnit and Kent Beck\'s
  6. Smalltalk testing framework.
  7.  
  8. This module contains the core framework classes that form the basis of
  9. specific test cases and suites (TestCase, TestSuite etc.), and also a
  10. text-based utility class for running the tests and reporting the results
  11.  (TextTestRunner).
  12.  
  13. Simple usage:
  14.  
  15.     import unittest
  16.  
  17.     class IntegerArithmenticTestCase(unittest.TestCase):
  18.         def testAdd(self):  ## test method names begin \'test*\'
  19.             self.assertEquals((1 + 2), 3)
  20.             self.assertEquals(0 + 1, 1)
  21.         def testMultiply(self):
  22.             self.assertEquals((0 * 10), 0)
  23.             self.assertEquals((5 * 8), 40)
  24.  
  25.     if __name__ == \'__main__\':
  26.         unittest.main()
  27.  
  28. Further information is available in the bundled documentation, and from
  29.  
  30.   http://pyunit.sourceforge.net/
  31.  
  32. Copyright (c) 1999-2003 Steve Purcell
  33. This module is free software, and you may redistribute it and/or modify
  34. it under the same terms as Python itself, so long as this copyright message
  35. and disclaimer are retained in their original form.
  36.  
  37. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
  38. SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
  39. THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  40. DAMAGE.
  41.  
  42. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
  43. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  44. PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
  45. AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
  46. SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  47. '''
  48. __author__ = 'Steve Purcell'
  49. __email__ = 'stephen_purcell at yahoo dot com'
  50. __version__ = '#Revision: 1.63 $'[11:-2]
  51. import time
  52. import sys
  53. import traceback
  54. import os
  55. import types
  56. __all__ = [
  57.     'TestResult',
  58.     'TestCase',
  59.     'TestSuite',
  60.     'TextTestRunner',
  61.     'TestLoader',
  62.     'FunctionTestCase',
  63.     'main',
  64.     'defaultTestLoader']
  65. __all__.extend([
  66.     'getTestCaseNames',
  67.     'makeSuite',
  68.     'findTestCases'])
  69. if sys.version_info[:2] < (2, 2):
  70.     (False, True) = (0, 1)
  71.     
  72.     def isinstance(obj, clsinfo):
  73.         import __builtin__
  74.         if type(clsinfo) in (tuple, list):
  75.             for cls in clsinfo:
  76.                 if cls is type:
  77.                     cls = types.ClassType
  78.                 
  79.                 if __builtin__.isinstance(obj, cls):
  80.                     return 1
  81.                     continue
  82.             
  83.             return 0
  84.         else:
  85.             return __builtin__.isinstance(obj, clsinfo)
  86.  
  87.  
  88. __metaclass__ = type
  89.  
  90. def _strclass(cls):
  91.     return '%s.%s' % (cls.__module__, cls.__name__)
  92.  
  93. __unittest = 1
  94.  
  95. class TestResult:
  96.     '''Holder for test result information.
  97.  
  98.     Test results are automatically managed by the TestCase and TestSuite
  99.     classes, and do not need to be explicitly manipulated by writers of tests.
  100.  
  101.     Each instance holds the total number of tests run, and collections of
  102.     failures and errors that occurred among those test runs. The collections
  103.     contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
  104.     formatted traceback of the error that occurred.
  105.     '''
  106.     
  107.     def __init__(self):
  108.         self.failures = []
  109.         self.errors = []
  110.         self.testsRun = 0
  111.         self.shouldStop = 0
  112.  
  113.     
  114.     def startTest(self, test):
  115.         '''Called when the given test is about to be run'''
  116.         self.testsRun = self.testsRun + 1
  117.  
  118.     
  119.     def stopTest(self, test):
  120.         '''Called when the given test has been run'''
  121.         pass
  122.  
  123.     
  124.     def addError(self, test, err):
  125.         """Called when an error has occurred. 'err' is a tuple of values as
  126.         returned by sys.exc_info().
  127.         """
  128.         self.errors.append((test, self._exc_info_to_string(err, test)))
  129.  
  130.     
  131.     def addFailure(self, test, err):
  132.         """Called when an error has occurred. 'err' is a tuple of values as
  133.         returned by sys.exc_info()."""
  134.         self.failures.append((test, self._exc_info_to_string(err, test)))
  135.  
  136.     
  137.     def addSuccess(self, test):
  138.         '''Called when a test has completed successfully'''
  139.         pass
  140.  
  141.     
  142.     def wasSuccessful(self):
  143.         '''Tells whether or not this result was a success'''
  144.         return None if len(self.errors) == len(self.errors) else len(self.errors) == 0
  145.  
  146.     
  147.     def stop(self):
  148.         '''Indicates that the tests should be aborted'''
  149.         self.shouldStop = True
  150.  
  151.     
  152.     def _exc_info_to_string(self, err, test):
  153.         '''Converts a sys.exc_info()-style tuple of values into a string.'''
  154.         (exctype, value, tb) = err
  155.         while tb and self._is_relevant_tb_level(tb):
  156.             tb = tb.tb_next
  157.         if exctype is test.failureException:
  158.             length = self._count_relevant_tb_levels(tb)
  159.             return ''.join(traceback.format_exception(exctype, value, tb, length))
  160.         
  161.         return ''.join(traceback.format_exception(exctype, value, tb))
  162.  
  163.     
  164.     def _is_relevant_tb_level(self, tb):
  165.         return tb.tb_frame.f_globals.has_key('__unittest')
  166.  
  167.     
  168.     def _count_relevant_tb_levels(self, tb):
  169.         length = 0
  170.         while tb and not self._is_relevant_tb_level(tb):
  171.             length += 1
  172.             tb = tb.tb_next
  173.         return length
  174.  
  175.     
  176.     def __repr__(self):
  177.         return '<%s run=%i errors=%i failures=%i>' % (_strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures))
  178.  
  179.  
  180.  
  181. class TestCase:
  182.     """A class whose instances are single test cases.
  183.  
  184.     By default, the test code itself should be placed in a method named
  185.     'runTest'.
  186.  
  187.     If the fixture may be used for many test cases, create as
  188.     many test methods as are needed. When instantiating such a TestCase
  189.     subclass, specify in the constructor arguments the name of the test method
  190.     that the instance is to execute.
  191.  
  192.     Test authors should subclass TestCase for their own tests. Construction
  193.     and deconstruction of the test's environment ('fixture') can be
  194.     implemented by overriding the 'setUp' and 'tearDown' methods respectively.
  195.  
  196.     If it is necessary to override the __init__ method, the base class
  197.     __init__ method must always be called. It is important that subclasses
  198.     should not change the signature of their __init__ method, since instances
  199.     of the classes are instantiated automatically by parts of the framework
  200.     in order to be run.
  201.     """
  202.     failureException = AssertionError
  203.     
  204.     def __init__(self, methodName = 'runTest'):
  205.         '''Create an instance of the class that will use the named test
  206.            method when executed. Raises a ValueError if the instance does
  207.            not have a method with the specified name.
  208.         '''
  209.         
  210.         try:
  211.             self._testMethodName = methodName
  212.             testMethod = getattr(self, methodName)
  213.             self._testMethodDoc = testMethod.__doc__
  214.         except AttributeError:
  215.             raise ValueError, 'no such test method in %s: %s' % (self.__class__, methodName)
  216.  
  217.  
  218.     
  219.     def setUp(self):
  220.         '''Hook method for setting up the test fixture before exercising it.'''
  221.         pass
  222.  
  223.     
  224.     def tearDown(self):
  225.         '''Hook method for deconstructing the test fixture after testing it.'''
  226.         pass
  227.  
  228.     
  229.     def countTestCases(self):
  230.         return 1
  231.  
  232.     
  233.     def defaultTestResult(self):
  234.         return TestResult()
  235.  
  236.     
  237.     def shortDescription(self):
  238.         """Returns a one-line description of the test, or None if no
  239.         description has been provided.
  240.  
  241.         The default implementation of this method returns the first line of
  242.         the specified test method's docstring.
  243.         """
  244.         doc = self._testMethodDoc
  245.         if not doc or doc.split('\n')[0].strip():
  246.             pass
  247.         return None
  248.  
  249.     
  250.     def id(self):
  251.         return '%s.%s' % (_strclass(self.__class__), self._testMethodName)
  252.  
  253.     
  254.     def __str__(self):
  255.         return '%s (%s)' % (self._testMethodName, _strclass(self.__class__))
  256.  
  257.     
  258.     def __repr__(self):
  259.         return '<%s testMethod=%s>' % (_strclass(self.__class__), self._testMethodName)
  260.  
  261.     
  262.     def run(self, result = None):
  263.         if result is None:
  264.             result = self.defaultTestResult()
  265.         
  266.         result.startTest(self)
  267.         testMethod = getattr(self, self._testMethodName)
  268.         
  269.         try:
  270.             self.setUp()
  271.         except KeyboardInterrupt:
  272.             raise 
  273.         except:
  274.             result.addError(self, self._exc_info())
  275.             return None
  276.         
  277.  
  278.         ok = False
  279.         
  280.         try:
  281.             testMethod()
  282.             ok = True
  283.         except self.failureException:
  284.             result.addFailure(self, self._exc_info())
  285.         except KeyboardInterrupt:
  286.             raise 
  287.         except:
  288.             result.addError(self, self._exc_info())
  289.  
  290.         
  291.         try:
  292.             self.tearDown()
  293.         except KeyboardInterrupt:
  294.             raise 
  295.         except:
  296.             result.addError(self, self._exc_info())
  297.             ok = False
  298.  
  299.         if ok:
  300.             result.addSuccess(self)
  301.         result.stopTest(self)
  302.  
  303.     
  304.     def __call__(self, *args, **kwds):
  305.         return self.run(*args, **kwds)
  306.  
  307.     
  308.     def debug(self):
  309.         '''Run the test without collecting errors in a TestResult'''
  310.         self.setUp()
  311.         getattr(self, self._testMethodName)()
  312.         self.tearDown()
  313.  
  314.     
  315.     def _exc_info(self):
  316.         '''Return a version of sys.exc_info() with the traceback frame
  317.            minimised; usually the top level of the traceback frame is not
  318.            needed.
  319.         '''
  320.         (exctype, excvalue, tb) = sys.exc_info()
  321.         if sys.platform[:4] == 'java':
  322.             return (exctype, excvalue, tb)
  323.         
  324.         return (exctype, excvalue, tb)
  325.  
  326.     
  327.     def fail(self, msg = None):
  328.         '''Fail immediately, with the given message.'''
  329.         raise self.failureException, msg
  330.  
  331.     
  332.     def failIf(self, expr, msg = None):
  333.         '''Fail the test if the expression is true.'''
  334.         if expr:
  335.             raise self.failureException, msg
  336.         
  337.  
  338.     
  339.     def failUnless(self, expr, msg = None):
  340.         '''Fail the test unless the expression is true.'''
  341.         if not expr:
  342.             raise self.failureException, msg
  343.         
  344.  
  345.     
  346.     def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
  347.         '''Fail unless an exception of class excClass is thrown
  348.            by callableObj when invoked with arguments args and keyword
  349.            arguments kwargs. If a different type of exception is
  350.            thrown, it will not be caught, and the test case will be
  351.            deemed to have suffered an error, exactly as for an
  352.            unexpected exception.
  353.         '''
  354.         
  355.         try:
  356.             callableObj(*args, **kwargs)
  357.         except excClass:
  358.             return None
  359.  
  360.         if hasattr(excClass, '__name__'):
  361.             excName = excClass.__name__
  362.         else:
  363.             excName = str(excClass)
  364.         raise self.failureException, '%s not raised' % excName
  365.  
  366.     
  367.     def failUnlessEqual(self, first, second, msg = None):
  368.         """Fail if the two objects are unequal as determined by the '=='
  369.            operator.
  370.         """
  371.         if not first == second:
  372.             if not msg:
  373.                 pass
  374.             raise self.failureException, '%r != %r' % (first, second)
  375.         
  376.  
  377.     
  378.     def failIfEqual(self, first, second, msg = None):
  379.         """Fail if the two objects are equal as determined by the '=='
  380.            operator.
  381.         """
  382.         if first == second:
  383.             if not msg:
  384.                 pass
  385.             raise self.failureException, '%r == %r' % (first, second)
  386.         
  387.  
  388.     
  389.     def failUnlessAlmostEqual(self, first, second, places = 7, msg = None):
  390.         '''Fail if the two objects are unequal as determined by their
  391.            difference rounded to the given number of decimal places
  392.            (default 7) and comparing to zero.
  393.  
  394.            Note that decimal places (from zero) are usually not the same
  395.            as significant digits (measured from the most signficant digit).
  396.         '''
  397.         if round(second - first, places) != 0:
  398.             if not msg:
  399.                 pass
  400.             raise self.failureException, '%r != %r within %r places' % (first, second, places)
  401.         
  402.  
  403.     
  404.     def failIfAlmostEqual(self, first, second, places = 7, msg = None):
  405.         '''Fail if the two objects are equal as determined by their
  406.            difference rounded to the given number of decimal places
  407.            (default 7) and comparing to zero.
  408.  
  409.            Note that decimal places (from zero) are usually not the same
  410.            as significant digits (measured from the most signficant digit).
  411.         '''
  412.         if round(second - first, places) == 0:
  413.             if not msg:
  414.                 pass
  415.             raise self.failureException, '%r == %r within %r places' % (first, second, places)
  416.         
  417.  
  418.     assertEqual = assertEquals = failUnlessEqual
  419.     assertNotEqual = assertNotEquals = failIfEqual
  420.     assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
  421.     assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
  422.     assertRaises = failUnlessRaises
  423.     assert_ = assertTrue = failUnless
  424.     assertFalse = failIf
  425.  
  426.  
  427. class TestSuite:
  428.     '''A test suite is a composite test consisting of a number of TestCases.
  429.  
  430.     For use, create an instance of TestSuite, then add test case instances.
  431.     When all tests have been added, the suite can be passed to a test
  432.     runner, such as TextTestRunner. It will run the individual test cases
  433.     in the order in which they were added, aggregating the results. When
  434.     subclassing, do not forget to call the base class constructor.
  435.     '''
  436.     
  437.     def __init__(self, tests = ()):
  438.         self._tests = []
  439.         self.addTests(tests)
  440.  
  441.     
  442.     def __repr__(self):
  443.         return '<%s tests=%s>' % (_strclass(self.__class__), self._tests)
  444.  
  445.     __str__ = __repr__
  446.     
  447.     def __iter__(self):
  448.         return iter(self._tests)
  449.  
  450.     
  451.     def countTestCases(self):
  452.         cases = 0
  453.         for test in self._tests:
  454.             cases += test.countTestCases()
  455.         
  456.         return cases
  457.  
  458.     
  459.     def addTest(self, test):
  460.         self._tests.append(test)
  461.  
  462.     
  463.     def addTests(self, tests):
  464.         for test in tests:
  465.             self.addTest(test)
  466.         
  467.  
  468.     
  469.     def run(self, result):
  470.         for test in self._tests:
  471.             if result.shouldStop:
  472.                 break
  473.             
  474.             test(result)
  475.         
  476.         return result
  477.  
  478.     
  479.     def __call__(self, *args, **kwds):
  480.         return self.run(*args, **kwds)
  481.  
  482.     
  483.     def debug(self):
  484.         '''Run the tests without collecting errors in a TestResult'''
  485.         for test in self._tests:
  486.             test.debug()
  487.         
  488.  
  489.  
  490.  
  491. class FunctionTestCase(TestCase):
  492.     """A test case that wraps a test function.
  493.  
  494.     This is useful for slipping pre-existing test functions into the
  495.     PyUnit framework. Optionally, set-up and tidy-up functions can be
  496.     supplied. As with TestCase, the tidy-up ('tearDown') function will
  497.     always be called if the set-up ('setUp') function ran successfully.
  498.     """
  499.     
  500.     def __init__(self, testFunc, setUp = None, tearDown = None, description = None):
  501.         TestCase.__init__(self)
  502.         self._FunctionTestCase__setUpFunc = setUp
  503.         self._FunctionTestCase__tearDownFunc = tearDown
  504.         self._FunctionTestCase__testFunc = testFunc
  505.         self._FunctionTestCase__description = description
  506.  
  507.     
  508.     def setUp(self):
  509.         if self._FunctionTestCase__setUpFunc is not None:
  510.             self._FunctionTestCase__setUpFunc()
  511.         
  512.  
  513.     
  514.     def tearDown(self):
  515.         if self._FunctionTestCase__tearDownFunc is not None:
  516.             self._FunctionTestCase__tearDownFunc()
  517.         
  518.  
  519.     
  520.     def runTest(self):
  521.         self._FunctionTestCase__testFunc()
  522.  
  523.     
  524.     def id(self):
  525.         return self._FunctionTestCase__testFunc.__name__
  526.  
  527.     
  528.     def __str__(self):
  529.         return '%s (%s)' % (_strclass(self.__class__), self._FunctionTestCase__testFunc.__name__)
  530.  
  531.     
  532.     def __repr__(self):
  533.         return '<%s testFunc=%s>' % (_strclass(self.__class__), self._FunctionTestCase__testFunc)
  534.  
  535.     
  536.     def shortDescription(self):
  537.         if self._FunctionTestCase__description is not None:
  538.             return self._FunctionTestCase__description
  539.         
  540.         doc = self._FunctionTestCase__testFunc.__doc__
  541.         if not doc or doc.split('\n')[0].strip():
  542.             pass
  543.  
  544.  
  545.  
  546. class TestLoader:
  547.     '''This class is responsible for loading tests according to various
  548.     criteria and returning them wrapped in a Test
  549.     '''
  550.     testMethodPrefix = 'test'
  551.     sortTestMethodsUsing = cmp
  552.     suiteClass = TestSuite
  553.     
  554.     def loadTestsFromTestCase(self, testCaseClass):
  555.         '''Return a suite of all tests cases contained in testCaseClass'''
  556.         if issubclass(testCaseClass, TestSuite):
  557.             raise TypeError('Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?')
  558.         
  559.         testCaseNames = self.getTestCaseNames(testCaseClass)
  560.         if not testCaseNames and hasattr(testCaseClass, 'runTest'):
  561.             testCaseNames = [
  562.                 'runTest']
  563.         
  564.         return self.suiteClass(map(testCaseClass, testCaseNames))
  565.  
  566.     
  567.     def loadTestsFromModule(self, module):
  568.         '''Return a suite of all tests cases contained in the given module'''
  569.         tests = []
  570.         for name in dir(module):
  571.             obj = getattr(module, name)
  572.             if isinstance(obj, (type, types.ClassType)) and issubclass(obj, TestCase):
  573.                 tests.append(self.loadTestsFromTestCase(obj))
  574.                 continue
  575.         
  576.         return self.suiteClass(tests)
  577.  
  578.     
  579.     def loadTestsFromName(self, name, module = None):
  580.         '''Return a suite of all tests cases given a string specifier.
  581.  
  582.         The name may resolve either to a module, a test case class, a
  583.         test method within a test case class, or a callable object which
  584.         returns a TestCase or TestSuite instance.
  585.  
  586.         The method optionally resolves the names relative to a given module.
  587.         '''
  588.         parts = name.split('.')
  589.         if module is None:
  590.             parts_copy = parts[:]
  591.             while parts_copy:
  592.                 
  593.                 try:
  594.                     module = __import__('.'.join(parts_copy))
  595.                 continue
  596.                 except ImportError:
  597.                     del parts_copy[-1]
  598.                     if not parts_copy:
  599.                         raise 
  600.                     
  601.                     parts_copy
  602.                 
  603.  
  604.                 None<EXCEPTION MATCH>ImportError
  605.             parts = parts[1:]
  606.         
  607.         obj = module
  608.         for part in parts:
  609.             parent = obj
  610.             obj = getattr(obj, part)
  611.         
  612.         if type(obj) == types.ModuleType:
  613.             return self.loadTestsFromModule(obj)
  614.         elif isinstance(obj, (type, types.ClassType)) and issubclass(obj, TestCase):
  615.             return self.loadTestsFromTestCase(obj)
  616.         elif type(obj) == types.UnboundMethodType:
  617.             return parent(obj.__name__)
  618.         elif isinstance(obj, TestSuite):
  619.             return obj
  620.         elif callable(obj):
  621.             test = obj()
  622.             if not isinstance(test, (TestCase, TestSuite)):
  623.                 raise ValueError, 'calling %s returned %s, not a test' % (obj, test)
  624.             
  625.             return test
  626.         else:
  627.             raise ValueError, "don't know how to make test from: %s" % obj
  628.  
  629.     
  630.     def loadTestsFromNames(self, names, module = None):
  631.         """Return a suite of all tests cases found using the given sequence
  632.         of string specifiers. See 'loadTestsFromName()'.
  633.         """
  634.         suites = [ self.loadTestsFromName(name, module) for name in names ]
  635.         return self.suiteClass(suites)
  636.  
  637.     
  638.     def getTestCaseNames(self, testCaseClass):
  639.         '''Return a sorted sequence of method names found within testCaseClass
  640.         '''
  641.         
  642.         def isTestMethod(attrname, testCaseClass = testCaseClass, prefix = self.testMethodPrefix):
  643.             if attrname.startswith(prefix):
  644.                 pass
  645.             return callable(getattr(testCaseClass, attrname))
  646.  
  647.         testFnNames = filter(isTestMethod, dir(testCaseClass))
  648.         for baseclass in testCaseClass.__bases__:
  649.             for testFnName in self.getTestCaseNames(baseclass):
  650.                 if testFnName not in testFnNames:
  651.                     testFnNames.append(testFnName)
  652.                     continue
  653.             
  654.         
  655.         if self.sortTestMethodsUsing:
  656.             testFnNames.sort(self.sortTestMethodsUsing)
  657.         
  658.         return testFnNames
  659.  
  660.  
  661. defaultTestLoader = TestLoader()
  662.  
  663. def _makeLoader(prefix, sortUsing, suiteClass = None):
  664.     loader = TestLoader()
  665.     loader.sortTestMethodsUsing = sortUsing
  666.     loader.testMethodPrefix = prefix
  667.     if suiteClass:
  668.         loader.suiteClass = suiteClass
  669.     
  670.     return loader
  671.  
  672.  
  673. def getTestCaseNames(testCaseClass, prefix, sortUsing = cmp):
  674.     return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
  675.  
  676.  
  677. def makeSuite(testCaseClass, prefix = 'test', sortUsing = cmp, suiteClass = TestSuite):
  678.     return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
  679.  
  680.  
  681. def findTestCases(module, prefix = 'test', sortUsing = cmp, suiteClass = TestSuite):
  682.     return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
  683.  
  684.  
  685. class _WritelnDecorator:
  686.     """Used to decorate file-like objects with a handy 'writeln' method"""
  687.     
  688.     def __init__(self, stream):
  689.         self.stream = stream
  690.  
  691.     
  692.     def __getattr__(self, attr):
  693.         return getattr(self.stream, attr)
  694.  
  695.     
  696.     def writeln(self, arg = None):
  697.         if arg:
  698.             self.write(arg)
  699.         
  700.         self.write('\n')
  701.  
  702.  
  703.  
  704. class _TextTestResult(TestResult):
  705.     '''A test result class that can print formatted text results to a stream.
  706.  
  707.     Used by TextTestRunner.
  708.     '''
  709.     separator1 = '=' * 70
  710.     separator2 = '-' * 70
  711.     
  712.     def __init__(self, stream, descriptions, verbosity):
  713.         TestResult.__init__(self)
  714.         self.stream = stream
  715.         self.showAll = verbosity > 1
  716.         self.dots = verbosity == 1
  717.         self.descriptions = descriptions
  718.  
  719.     
  720.     def getDescription(self, test):
  721.         if self.descriptions:
  722.             if not test.shortDescription():
  723.                 pass
  724.             return str(test)
  725.         else:
  726.             return str(test)
  727.  
  728.     
  729.     def startTest(self, test):
  730.         TestResult.startTest(self, test)
  731.         if self.showAll:
  732.             self.stream.write(self.getDescription(test))
  733.             self.stream.write(' ... ')
  734.         
  735.  
  736.     
  737.     def addSuccess(self, test):
  738.         TestResult.addSuccess(self, test)
  739.         if self.showAll:
  740.             self.stream.writeln('ok')
  741.         elif self.dots:
  742.             self.stream.write('.')
  743.         
  744.  
  745.     
  746.     def addError(self, test, err):
  747.         TestResult.addError(self, test, err)
  748.         if self.showAll:
  749.             self.stream.writeln('ERROR')
  750.         elif self.dots:
  751.             self.stream.write('E')
  752.         
  753.  
  754.     
  755.     def addFailure(self, test, err):
  756.         TestResult.addFailure(self, test, err)
  757.         if self.showAll:
  758.             self.stream.writeln('FAIL')
  759.         elif self.dots:
  760.             self.stream.write('F')
  761.         
  762.  
  763.     
  764.     def printErrors(self):
  765.         if self.dots or self.showAll:
  766.             self.stream.writeln()
  767.         
  768.         self.printErrorList('ERROR', self.errors)
  769.         self.printErrorList('FAIL', self.failures)
  770.  
  771.     
  772.     def printErrorList(self, flavour, errors):
  773.         for test, err in errors:
  774.             self.stream.writeln(self.separator1)
  775.             self.stream.writeln('%s: %s' % (flavour, self.getDescription(test)))
  776.             self.stream.writeln(self.separator2)
  777.             self.stream.writeln('%s' % err)
  778.         
  779.  
  780.  
  781.  
  782. class TextTestRunner:
  783.     '''A test runner class that displays results in textual form.
  784.  
  785.     It prints out the names of tests as they are run, errors as they
  786.     occur, and a summary of the results at the end of the test run.
  787.     '''
  788.     
  789.     def __init__(self, stream = sys.stderr, descriptions = 1, verbosity = 1):
  790.         self.stream = _WritelnDecorator(stream)
  791.         self.descriptions = descriptions
  792.         self.verbosity = verbosity
  793.  
  794.     
  795.     def _makeResult(self):
  796.         return _TextTestResult(self.stream, self.descriptions, self.verbosity)
  797.  
  798.     
  799.     def run(self, test):
  800.         '''Run the given test case or test suite.'''
  801.         result = self._makeResult()
  802.         startTime = time.time()
  803.         test(result)
  804.         stopTime = time.time()
  805.         timeTaken = stopTime - startTime
  806.         result.printErrors()
  807.         self.stream.writeln(result.separator2)
  808.         run = result.testsRun
  809.         if not run != 1 or 's':
  810.             pass
  811.         self.stream.writeln('Ran %d test%s in %.3fs' % (run, '', timeTaken))
  812.         self.stream.writeln()
  813.         if not result.wasSuccessful():
  814.             self.stream.write('FAILED (')
  815.             (failed, errored) = map(len, (result.failures, result.errors))
  816.             if failed:
  817.                 self.stream.write('failures=%d' % failed)
  818.             
  819.             if errored:
  820.                 if failed:
  821.                     self.stream.write(', ')
  822.                 
  823.                 self.stream.write('errors=%d' % errored)
  824.             
  825.             self.stream.writeln(')')
  826.         else:
  827.             self.stream.writeln('OK')
  828.         return result
  829.  
  830.  
  831.  
  832. class TestProgram:
  833.     '''A command-line program that runs a set of tests; this is primarily
  834.        for making test modules conveniently executable.
  835.     '''
  836.     USAGE = "Usage: %(progName)s [options] [test] [...]\n\nOptions:\n  -h, --help       Show this message\n  -v, --verbose    Verbose output\n  -q, --quiet      Minimal output\n\nExamples:\n  %(progName)s                               - run default set of tests\n  %(progName)s MyTestSuite                   - run suite 'MyTestSuite'\n  %(progName)s MyTestCase.testSomething      - run MyTestCase.testSomething\n  %(progName)s MyTestCase                    - run all 'test*' test methods\n                                               in MyTestCase\n"
  837.     
  838.     def __init__(self, module = '__main__', defaultTest = None, argv = None, testRunner = None, testLoader = defaultTestLoader):
  839.         if type(module) == type(''):
  840.             self.module = __import__(module)
  841.             for part in module.split('.')[1:]:
  842.                 self.module = getattr(self.module, part)
  843.             
  844.         else:
  845.             self.module = module
  846.         if argv is None:
  847.             argv = sys.argv
  848.         
  849.         self.verbosity = 1
  850.         self.defaultTest = defaultTest
  851.         self.testRunner = testRunner
  852.         self.testLoader = testLoader
  853.         self.progName = os.path.basename(argv[0])
  854.         self.parseArgs(argv)
  855.         self.runTests()
  856.  
  857.     
  858.     def usageExit(self, msg = None):
  859.         if msg:
  860.             print msg
  861.         
  862.         print self.USAGE % self.__dict__
  863.         sys.exit(2)
  864.  
  865.     
  866.     def parseArgs(self, argv):
  867.         import getopt
  868.         
  869.         try:
  870.             (options, args) = getopt.getopt(argv[1:], 'hHvq', [
  871.                 'help',
  872.                 'verbose',
  873.                 'quiet'])
  874.             for opt, value in options:
  875.                 if opt in ('-h', '-H', '--help'):
  876.                     self.usageExit()
  877.                 
  878.                 if opt in ('-q', '--quiet'):
  879.                     self.verbosity = 0
  880.                 
  881.                 if opt in ('-v', '--verbose'):
  882.                     self.verbosity = 2
  883.                     continue
  884.             
  885.             if len(args) == 0 and self.defaultTest is None:
  886.                 self.test = self.testLoader.loadTestsFromModule(self.module)
  887.                 return None
  888.             
  889.             if len(args) > 0:
  890.                 self.testNames = args
  891.             else:
  892.                 self.testNames = (self.defaultTest,)
  893.             self.createTests()
  894.         except getopt.error:
  895.             msg = None
  896.             self.usageExit(msg)
  897.  
  898.  
  899.     
  900.     def createTests(self):
  901.         self.test = self.testLoader.loadTestsFromNames(self.testNames, self.module)
  902.  
  903.     
  904.     def runTests(self):
  905.         if self.testRunner is None:
  906.             self.testRunner = TextTestRunner(verbosity = self.verbosity)
  907.         
  908.         result = self.testRunner.run(self.test)
  909.         sys.exit(not result.wasSuccessful())
  910.  
  911.  
  912. main = TestProgram
  913. if __name__ == '__main__':
  914.     main(module = None)
  915.  
  916.